package org.finesys.samples.file.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Scanner;

public class AioClient {

    public static void main(String[] args) {

        try {
            AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
            socketChannel.connect(new InetSocketAddress("localhost",9090), null, new CompletionHandler<Void, Object>() {
                @Override
                public void completed(Void result, Object attachment) {
                    System.out.println("连接到服务端");
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("连接失败");
                }
            });
            //从键盘读取输入消息
            Scanner scanner = new Scanner(System.in);
            System.out.println("输入消息：");
            String message = scanner.nextLine();
            //写入数据到异步套接字通道
            socketChannel.write(ByteBuffer.wrap(message.getBytes()), null, new CompletionHandler<Integer, Object>() {
                @Override
                public void completed(Integer result, Object attachment) {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer, byteBuffer, new ReadCompletionHandler(socketChannel));
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("写入消息失败");
                }
            });
            //保持客户端开启
            Thread.sleep(Integer.MAX_VALUE);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
